Securing MongoDB with Masterkey or SA account
21 January, 2017 mongodb nosqlSince resent events an unsecured MongoDB Server in the open is not a good security practice and by default no system account or database user account is created when MongoDB is installed, you need to do it by yourself. It's not that difficult but another step to do.
I will go over the steps on a Windows installation of MongoDB. I assume you have installed MongoDB with the MSI Installer and run it as a Windows Service.
We are now going to create a MongoDB user which has full access to the MongoDB Server. This means all databases available on this server and databases that will be created in the future. Hence the database masterkey/system administrator paradigm.
Now start the mongo shell (mongo.exe from the program files folder) and enter the following statements
use admin
db.createUser(
{
user: "admin" ,
pwd: "**************",
roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"]
}
)
Now we need to re-start the MongoDB server but with security enforcement enabled by default. On Windows we can do this by editing the registry or changing the config file if used. I show you how to do this in the registry.
Start regedit.exe
Go to 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MongoDB'
Locate the 'Imagepath' key with '"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --logpath "C:\data\logs\log.txt" --dbpath "C:\data\db" --service'
and change it into '"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --logpath "C:\data\logs\log.txt" --dbpath "C:\data\db" --service --auth'
Close the mongo shell
Restart the MongoDB in the Task Manager Services Tab
And reconnect with the mongo shell and authenticate
db.auth("admin", "***********")
You are now connected to a secure MongoDB server and when running this public users need to authenticate. To further strengthen security, it's advisable to create a more granular security access to your MongoDB Server/Databases by creating more users with lesser security roles. See for more details the MongoDB Manuals.
When running your server public it is also a good practise to use a ssl connection to your MongoDB server but this requires another post.